﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Projections.Services;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Projections.Descriptors.Layout;
using Orchard.Projections.Models;

namespace EMS.Calendar.Providers.Layouts {
    public class CalendarLayout : ILayoutProvider {
        private readonly IContentManager _contentManager;
        protected dynamic Shape { get; set; }

        public CalendarLayout(IShapeFactory shapeFactory, IContentManager contentManager) {
            _contentManager = contentManager;
            Shape = shapeFactory;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(DescribeLayoutContext describe) {
            describe.For("Html", T("Html"), T("Html Layouts"))
                .Element("Calendar", T("Html Calendar"), T("Display content items inside a calendar."),
                    DisplayLayout,
                    RenderLayout,
                    "CalendarLayout"
                );
        }

        public LocalizedString DisplayLayout(LayoutContext context) {
            // May be more advanced in the future with different display types
            return T("Html Calendar");
        }

        public dynamic RenderLayout(LayoutContext context, IEnumerable<LayoutComponentResult> layoutComponentResults) {
            string order = context.State.Order;
            string itemClass = context.State.ItemClass;
            string listClass = context.State.ListClass;
            string listId = context.State.ListId;

            string listTag = order == "ordered" ? "ol" : "ul";

            IEnumerable<dynamic> shapes;
            if (context.LayoutRecord.Display == (int)LayoutRecord.Displays.Content) {
                shapes = layoutComponentResults.Select(x => _contentManager.BuildDisplay(x.ContentItem, context.LayoutRecord.DisplayType));
            }
            else {
                shapes = layoutComponentResults.Select(x => x.Properties);
            }

            var classes = String.IsNullOrEmpty(listClass) ? Enumerable.Empty<string>() : new[] { listClass };
            var itemClasses = String.IsNullOrEmpty(itemClass) ? Enumerable.Empty<string>() : new[] { itemClass };

            return Shape.List(Id: listId, Items: shapes, Tag: listTag, Classes: classes, ItemClasses: itemClasses);
        }

    }
}